package org.wkg.lesson08;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 1.写任务与时间的类方法
 * 2.组织任务
 * 3.创建一个创建任务的方法
 * 4.写一个线程来运行
 */

public class MyTimer_7 {
    private BlockingQueue<MyTask07> queue = new PriorityBlockingQueue<>();

    private Object loker = new Object();

    public MyTimer_7() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    MyTask07 task = this.queue.take();
                    long time = task.getTime();
                    if (time <= System.currentTimeMillis()) {
                        task.getRunnable().run();
                    } else {
                        long waittime = task.getTime() - System.currentTimeMillis();
                        queue.put(task);
                        synchronized (loker) {
                            loker.wait(waittime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();

        Thread deamonThread = new Thread(() -> {
               while (true){
                   synchronized(loker){
                       loker.notifyAll();
                   }
                   try {
                       TimeUnit.MILLISECONDS.sleep(100);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
        });
        deamonThread.setDaemon(true);
        deamonThread.start();
    }


    public void schedule(Runnable runnable, long delay) throws InterruptedException {
        MyTask07 task = new MyTask07(runnable, delay);
        queue.put(task);
        synchronized (loker) {
            loker.notifyAll();
        }
    }

}


class MyTask07 implements Comparable<MyTask07> {
    private Runnable runnable;
    private long time;

    public MyTask07(Runnable runnable, long delay) {
        if (runnable == null) {
            throw new IllegalArgumentException("任务不可以为null");
        }
        if (delay < 0) {
            throw new IllegalArgumentException("任务时间不能小于0");
        }
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask07 o) {
        if (getTime() > o.getTime()) {
            return 1;
        } else if (getTime() < o.getTime()) {
            return -1;
        } else {
            return 0;
        }
    }
}
